//
//  OAuthViewController.swift
//  
//
//  Created by zz on 16/2/28.
//
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {

    private lazy var webView: UIWebView = UIWebView()
    override func loadView() {
        
        view = webView
        webView.delegate = self
        
        title = "新浪微博"
        
        // 设置导航栏
        title = "登录新浪微博"
        //navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(16)]
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "取消",
            style: .Plain,
            target: self,
            action: "clickCloseButton")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "自动填充",
            style: .Plain,
            target: self,
            action: "clickAutoFillButton")
        

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
         // 在纯代码开发中，所有的 view 都要指定背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }

    //MARK: - method
    func clickCloseButton(){
    
        dismissViewControllerAnimated(true, completion: nil)

    }
    
    func clickAutoFillButton(){
    
        let js = "document.getElementById('userId').value='18650707492@sina.cn';" +
        "document.getElementById('passwd').value='qaz123';"
        
        // 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
extension OAuthViewController: UIWebViewDelegate{

     /// 将要开始加载请求，每次加载新的页面时，都会被调用，执行当前页面的js不会被调用,一般返回YES
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 1. 如果 URL 不是 回调地址，就继续加载页面
        
        if let urlString = request.URL?.absoluteString
            where !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri){
            print(urlString)
                return true
        }
        // 2. 否则判断回调参数，如果授权成功,则 URL 的`查询字符串`中包含 code 参数
//         query 是 URL `?` 后面所有的内容
        guard let query = request.URL?.query where query.hasPrefix("code=") else {
            print("取消授权")
            dismissViewControllerAnimated(true, completion: nil)
            
            return false
        }
         
        print("请求字符串 " + query)
        
        // 2> 获得请求码
        let code = query.substringFromIndex("code=".endIndex)
        print("请求字符串 " + code)
    
        NetworkTools.sharedTools.loadAccessToken(code) { (result) in
            
            guard let result = result else {
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                print("您的网络不给力")
                return
            }
//            print("\(result)")
            
            // 设置用户账户单例的数据
            UserAccount.sharedUserAccount.updateUserAccount(result)

            //登录成功(通知)不使用代理（一对一）
            NSNotificationCenter.defaultCenter().postNotificationName(ZDMircoblogSuccessedNotification, object: nil)
            SVProgressHUD.showInfoWithStatus("登录成功")
            

            delay(block: { 
                self.clickCloseButton()
            })

        }
        return false
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
